#!/usr/bin/python3

# SPDX-FileCopyrightText: Red Hat, Inc.
# SPDX-License-Identifier: GPL-2.0-or-later

# cat <<EOF | vdsm-client VM create -f -
# {
#     "vmID": "33aa53ea-c262-4e96-9e19-7555838d0fcf",
#     "vmParams": {
#                 "memSize": "20",
#                 "display": "vnc",
#                 "vmName": "bla"
#     }
# }
# EOF

from __future__ import absolute_import
from __future__ import print_function

import argparse
import json
import sys
import uuid

from vdsm import client


_HOST = '127.0.0.1'
_PORT = 54321


def _read_conf(args):
    conf = {}
    for filename in args.config:
        try:
            with open(filename, 'rt') as src:
                conf.update(json.load(src))
        except IOError:
            sys.stderr.write('%r not found, skipped\n' % filename)
    return conf


def _update_conf(conf, args, default_uuid):
    vm_uuid = uuid.UUID(args.id)
    vm_name = args.name
    if vm_name == default_uuid and vm_uuid != default_uuid:
        vm_name = str(vm_uuid)

    conf['vmId'] = str(vm_uuid)
    conf['vmName'] = vm_name
    if args.fix_device_ids:
        for dev_conf in conf.get('devices', []):
            dev_conf['deviceId'] = str(uuid.uuid4())

    return conf


def main():
    default_uuid = str(uuid.uuid4())
    parser = argparse.ArgumentParser('run a vm from the command line')
    parser.add_argument('--host', type=str,
                        default=_HOST,
                        help='hostname to connect')
    parser.add_argument('--port', type=int,
                        default=_PORT,
                        help='port to connect')
    parser.add_argument('--no-tls',
                        action='store_true',
                        help='do NOT use TLS to connect')
    parser.add_argument('--name', type=str,
                        default=default_uuid,
                        help='vm name')
    parser.add_argument('--id', type=str,
                        default=default_uuid,
                        help='vm uuid')
    parser.add_argument('--fix-device-ids',
                        action='store_true',
                        help='update each deviceId')
    parser.add_argument('--config', type=str,
                        nargs='+',
                        default=['vmconfig.json'],
                        help='vm configuration, JSON format')
    args = parser.parse_args()

    conf = _read_conf(args)
    conf = _update_conf(conf, args, default_uuid)

    use_tls = not args.no_tls
    serv = client.connect(
        host=args.host,
        port=args.port,
        use_tls=use_tls,
    )

    serv.VM.create(vmID=conf['vmId'], vmParams=conf)

    print(conf['vmId'])


if __name__ == '__main__':
    main()
